﻿using LPLS.Commons.DBModule;
using LPLS.DBEntities;
using LPLS.DBEntities.ConfigModels.AlarmModels.AlarmVarableCodeRuleConfigModels;
using LPLS.DBEntities.ConfigModels.DataCollectionConfigModule.DataCollectionRuleEdgeModule;
using LPLS.DBInterface.ConfigModels.DataCollectionConfigModule.DataCollectionRuleEdgeModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace LPLS.DBServices.ConfigModels.DataCollectionConfigModule.DataCollectionRuleEdgeModule
{
    internal class DataCollectionRuleConfigService : DBBaseService, IDataCollectionRuleConfigService
    {
        public DataCollectionRuleConfigService(DBContext dbContext) : base(dbContext)
        {
        }

        public int AddData(DataCollectionWorkFlowConfig model)
        {
            using var tran = this.Client.UseTran();//using不能少

            var delete = this.Client.DeleteNav<DataCollectionWorkFlowConfig>(it => it.DeviceID == model.DeviceID && it.CompentID == model.CompentID)
                            .Include(z1 => z1.Rules)
                            .ExecuteCommand();
            var result = this.Client.InsertNav(model)
                              .Include(z1 => z1.Rules)
                              .ExecuteCommand();

            tran.CommitTran();//commitTran提交，如果没有提交成功会自动回滚

            if (delete&&result)
            {
                return 1;
            }
            return 0;
        }

        public int DeleteData(Guid deviceid, Guid CompentId)
        {
            return this.Client.DeleteNav<DataCollectionWorkFlowConfig>(it => it.DeviceID==deviceid&&it.CompentID==CompentId)
                              .Include(z1 => z1.Rules)
                              .ExecuteCommand() == true ? 1 : 0;

        }

        public List<DataCollectionWorkFlowConfig> GetData()
        {
            return this.Client.Queryable<DataCollectionWorkFlowConfig>()
                               .Includes(x => x.Rules)
                               .ToList();
        }

        public List<DataCollectionWorkFlowConfig> GetData(Guid deviceid, Guid CompentId)
        {
            return this.Client.Queryable<DataCollectionWorkFlowConfig>()
                               .Includes(x => x.Rules)
                               .Where(x => x.DeviceID == deviceid && x.CompentID == CompentId)
                               .ToList();
        }

        public override void InitDataBaseName()
        {
            DataBaseName = DatabaseEnum.CollectionConfigDB.ToString();
        }

        public int UpdateData(DataCollectionWorkFlowConfig model)
        {
            return this.Client.UpdateNav(model)
                              .Include(x => x.Rules)//默认
                              .ExecuteCommand() == true ? 1 : 0;
        }
    }
}
